package com.point.business.servlets;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.point.business.database.model.User;
import com.point.business.util.Role;

/**
 * Servlet Filter implementation class SecurityFilter
 */

public class SecurityFilter implements Filter {
	private static Logger logger = Logger.getLogger(SecurityFilter.class);

	/**
	 * Default constructor.
	 */
	public SecurityFilter() {
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		String uri = httpRequest.getRequestURI();
		int indexOfLastSlash = uri.lastIndexOf("/");
		String uriWithoutPage = uri.substring(0, indexOfLastSlash);
		String pageName = uri.substring(uri.lastIndexOf("/") + 1);
		String folderName = uriWithoutPage.substring(uriWithoutPage
				.lastIndexOf("/") + 1);

		if (pageName.equals("") || pageName.startsWith("index")
				|| pageName.startsWith("error") || pageName.startsWith("main")) {
			chain.doFilter(request, response);
		} else {
			User user = (User) httpRequest.getSession().getAttribute("user");
			if (user == null) {
				redirectToErrorPage(httpRequest, httpResponse);
			} else {
				if (user.getRole() == Role.ADMIN
						&& folderName.startsWith("admin")) {
					chain.doFilter(request, response);
				} else if (user.getRole() == Role.USER
						&& folderName.startsWith("user")) {
					chain.doFilter(request, response);
				} else {
					redirectToErrorPage(httpRequest, httpResponse);
				}
			}
		}
	}

	private void redirectToErrorPage(HttpServletRequest request,
			HttpServletResponse response) {
		logger.warn("The following IP address: " + request.getRemoteAddr()
				+ " tried to enter the site with incorrect priveleges");
		try {
			response.sendRedirect(request.getContextPath() + "/error.jsp?errorMessage=doNotHavePrivelegesLogin");
		} catch (IOException e) {
			logger.error(e);
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
	}

}
